package sz.szsmk.citizencard.ui.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.IdRes;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;

import java.text.DecimalFormat;

import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.util.StringCommonUtil;
import sz.szsmk.citizencard.dialog.ConnectRequestTipsDialog;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.bean.request.PowerCheckOrderReq;
import sz.szsmk.citizencard.model.network.bean.request.PowerGetMac2Req;
import sz.szsmk.citizencard.model.network.bean.request.PowerRechargeReq;
import sz.szsmk.citizencard.model.network.bean.response.PowerCheckOrderRes;
import sz.szsmk.citizencard.model.network.bean.response.PowerGetMac2Res;
import sz.szsmk.citizencard.model.network.bean.response.PowerRechargeRes;
import sz.szsmk.citizencard.retrofitrxjava.ErrorAction;
import sz.szsmk.citizencard.retrofitrxjava.NetworkDateSources;
import sz.szsmk.citizencard.retrofitrxjava.SubscribeResult;
import sz.szsmk.citizencard.ui.base.AppManager;
import sz.szsmk.citizencard.ui.base.SuperActivity;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.widget.CashierInputFilter;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/6/29 16:50
 * description：卡片详情页面
 */
public class CardInfoActivity extends SuperActivity {

    private String TAG = CardInfoActivity.class.getSimpleName();
    private TextView textBalance;
    private TextView cardNnm;
    private Button btn_write;

    private LinearLayout progressLayout;

    private LinearLayout btnBack;
    private TextView textTitle;
    private TextView text_right;

    private RelativeLayout order;
    private TextView recharge;
    private TextView orderNo;
    private TextView id_cardNo;
    private TextView recharge_type;
    private TextView pay_type;
    private TextView time;
    private TextView mpOrderStatusStr;

    private boolean isPaying = false;
    private RelativeLayout rlRecharge;
    private Button btnRecharge;
    private EditText etRecharge;
    private EditText etPwd;
    private RadioGroup rg_mode;
    private RadioButton pm_zfb;
    private RadioButton pm_czk;
    private RadioButton pm_zyzh;
    private int mode = 0;


    private ConnectRequestTipsDialog connectRequestTipsDialog;

    private RelativeLayout no_card;
    private Button btn_read_card;

    private static String PROCARDNO="1C0000000055";
    private static String CITYCARDNO="1C0000000010";
    private int cardOldBalance=0;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String message = (String) msg.obj;
            DecimalFormat df = new DecimalFormat("#.00");

            switch (msg.what) {
                case 0:
                    dismissLoadingDialog();
                    no_card.setVisibility(View.VISIBLE);
                    Toast.makeText(CardInfoActivity.this,"未读取到卡片，请将卡片放置读卡区域",Toast.LENGTH_LONG).show();
//                    progressLayout.setVisibility(View.GONE);
                    break;
                case 1:

                    try{
                        if(isProCard){
                            cardNo =   message.substring(21,40);
                            asn=message.substring(20,40);
                        }else{
                            cardNo =   message.substring(0,16);
                            asn=message.substring(20,40);
                        }
                        cardNnm.setText("IC No：" + cardNo);
                       // readBalance();
                        readCardDetailSecond();
                    }catch (Exception e){
                        dismissLoadingDialog();
                    }



  //                  writePackage();
                    break;
                case 2:
                    if(message.length()>8){
                        message = message.substring(0,8);
                        try{
                            cardOldBalance = Integer.valueOf(message,16);
                            cardOldBal =df.format((double)cardOldBalance/100)+"";
                            textBalance.setText(cardOldBal);
                            readCardTrade();
                        }catch (Exception e){
                            textBalance.setText("");
                            no_card.setVisibility(View.VISIBLE);
                            Toast.makeText(CardInfoActivity.this,"余额读取失败...",Toast.LENGTH_LONG).show();
                            dismissLoadingDialog();
                        }



                    }else{
                        no_card.setVisibility(View.VISIBLE);
                        Toast.makeText(CardInfoActivity.this,"余额读取失败...",Toast.LENGTH_LONG).show();
                        dismissLoadingDialog();
                    }

 //                   read15();
                    break;
                case 3:
                    if(message.length()>8){
                        cardTradeNo = message.substring(8,12);
                        prepayCheck();
                    }else{
                        no_card.setVisibility(View.VISIBLE);
                        Toast.makeText(CardInfoActivity.this,"交易账号读取失败...",Toast.LENGTH_LONG).show();
                        dismissLoadingDialog();
                    }

//                    read15Information();
                    break;
                case 4:
                    if(message.length()>8){
                        cardTradeNo =message.substring(8,12);
                        keyVersion = message.substring(12, 14);
                        arithIndex = message.substring(14, 16);
                        rndnumber2 = message.substring(16, 24);
                        mac1 = message.substring(24, 32);
                        requestMac2();
                    }else{
                        Toast.makeText(CardInfoActivity.this,"充值成功",Toast.LENGTH_LONG).show();
                        dismissLoadingDialog();
                    }
    //                read16Information();
                    break;
                case 5:
                    pm_zfb.setChecked(false);
                    pm_czk.setChecked(false);
                    pm_zyzh.setChecked(false);
                    etRecharge.setVisibility(View.GONE);
                    etPwd.setVisibility(View.GONE);
                    loadCardInfo();
                    Toast.makeText(CardInfoActivity.this,R.string.recharge_successed,Toast.LENGTH_LONG).show();
  //                  test();
                    break;

                case 15:
                    progressLayout.setVisibility(View.GONE);
                    dismissLoadingDialog();
                    handlerAipay();
                    break;

                case RQF_PAY:
                    loadCardInfo();
                    break;
                default:
                    break;
            }
        }
    };
    private String value;

    private NetworkDateSources mNetworkDateSource;
    private String access_token;
    private String extend;
    private PowerCheckOrderRes.TermAllVerifyInfoBean termAllVerifyInfo;
    private int tradeMoney = 0;
    private PowerGetMac2Res powerGetMac2Res;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_info);
        mNetworkDateSource = NetworkDateSources.getInstance();
        findViewId();
        initData();
        setListener();
        loadCardInfo();
    }



    @Override
    protected void findViewId() {
        btnBack = (LinearLayout) findViewById(R.id.layout_back);
        textTitle = (TextView) findViewById(R.id.txt_title);
        text_right = (TextView) findViewById(R.id.text_right);
        cardNnm = (TextView) findViewById(R.id.cardNnm);

        textBalance = (TextView) findViewById(R.id.text_balance);
        btn_write = (Button) findViewById(R.id.btn_write);
        progressLayout = (LinearLayout) findViewById(R.id.progress_layout);
        order = (RelativeLayout) findViewById(R.id.order);
        recharge = (TextView) findViewById(R.id.recharge);
        orderNo = (TextView) findViewById(R.id.orderNo);
        id_cardNo = (TextView) findViewById(R.id.id_cardNo);
        recharge_type = (TextView) findViewById(R.id.recharge_type);
        mpOrderStatusStr = (TextView) findViewById(R.id.mpOrderStatusStr);
        pay_type = (TextView) findViewById(R.id.pay_type);
        time = (TextView) findViewById(R.id.time);
        rlRecharge = (RelativeLayout) findViewById(R.id.rl_recharge);
        etRecharge = (EditText) findViewById(R.id.et_recharge);
        InputFilter[] is = {new CashierInputFilter()};
        etRecharge.setFilters(is);
        etPwd = (EditText) findViewById(R.id.et_password);
        btnRecharge = (Button) findViewById(R.id.btn_recharge);

        no_card = (RelativeLayout) findViewById(R.id.no_card);
        btn_read_card = (Button) findViewById(R.id.btn_read_card);
        rg_mode = (RadioGroup) findViewById(R.id.rg_mode);
        pm_zfb = (RadioButton) findViewById(R.id.pm_zfb);
        pm_czk = (RadioButton) findViewById(R.id.pm_czk);
        pm_zyzh = (RadioButton) findViewById(R.id.pm_zyzh);
        no_card.setVisibility(View.VISIBLE);
        progressLayout.setVisibility(View.GONE);
        textBalance.setText("");
        order.setVisibility(View.GONE);
        rlRecharge.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {
        access_token = ACache.get(this).getAsString("access_token");
        textTitle.setText("卡信息");
        text_right.setText("刷新");
//        userId = SharedPreferenceSetting.getUserId(this);
        userId = "602074";
    //    findCard();

    }

    public void showLoadDialog(String title) {
        if (null == connectRequestTipsDialog) {
            connectRequestTipsDialog = new ConnectRequestTipsDialog();
//            progressDialog = new CustomProgressDialog(this);
//            progressDialog.show();
            Bundle bundle = new Bundle();
            bundle.putString("title",title);
            connectRequestTipsDialog.setArguments(bundle);
        }

        android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(connectRequestTipsDialog, this.getClass().getSimpleName());
        ft.commitAllowingStateLoss();
    }

    public void dismissLoadingDialog() {
        if (null != connectRequestTipsDialog) {
            connectRequestTipsDialog.dismissAllowingStateLoss();
            connectRequestTipsDialog = null;
        }
//        if (null != progressDialog) {
//            progressDialog.dismiss();
//            progressDialog = null;
//        }
    }
    private void loadCardInfo(){
        order.setVisibility(View.GONE);
        showLoadDialog("正在读卡...");
        new Thread(new Runnable() {
            @Override
            public void run() {


            }
        }).start();
    }
    private void getAccountInfo(){
        new Thread(new Runnable() {
            @Override
            public void run() {
            }
        }).start();
    }
    private void getFileInfo(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        checkCardState();
                    }
                });

            }
        }).start();
    }
    private boolean isProCard;//是否是省卡

    private void checkCardState(){
        new Thread(new Runnable() {
            @Override
            public void run() {

            }
        }).start();
    }

    private void readCardInfo(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                if(isProCard){
                    readProCardInfo();
                }else{
                    readCardDetail();
                }


            }
        }).start();
    }

    private void readProCardInfo(){

        new Thread(new Runnable() {
            @Override
            public void run() {
            }
        }).start();


    }
    private void readCardDetail(){

        new Thread(){
            @Override
            public void run() {
                String targetInfo="";

            }
        }.start();
    }

    private void readCardDetailSecond(){


        new Thread(){
            @Override
            public void run() {


            }
        }.start();
    }
    private void readBalance(){

    }
    private void readCardTrade(){


    }



    private void getCardTradeInfo(String balance){
    }
    private void writeCardInfo(){
    }
    private void prepayCheck() {
        PowerCheckOrderReq powerCheckOrderReq = new PowerCheckOrderReq();
        powerCheckOrderReq.setCard_no(cardNo);
        powerCheckOrderReq.setCard_old_balance(cardOldBalance+"");
        powerCheckOrderReq.setAccess_token(access_token);
        powerCheckOrderReq.setCard_trade_no(cardTradeNo.toUpperCase());
        String json = new Gson().toJson(powerCheckOrderReq);
        L.e(Constant.TAG, "termAllVerify----->" + json);
        mNetworkDateSource.termAllVerify(powerCheckOrderReq, new SubscribeResult<PowerCheckOrderRes>() {
            @Override
            protected void onOk(PowerCheckOrderRes response) {

                dismissLoadingDialog();
                termAllVerifyInfo = response.getTermAllVerifyInfo();
                tradeMoney = termAllVerifyInfo.getTransMoney();
                L.e(Constant.TAG, "获取到订单金额：" + tradeMoney);
                if (response.getTermAllVerifyInfo() != null) {
                    order.setVisibility(View.VISIBLE);
                    rlRecharge.setVisibility(View.GONE);
                    no_card.setVisibility(View.GONE);
                    DecimalFormat df = new DecimalFormat("#.00");
                    recharge.setText(df.format((double)tradeMoney / 100) + "元");
                    orderNo.setText("订单号：" + termAllVerifyInfo.getOrderNo());
                    id_cardNo.setText("卡号：" + termAllVerifyInfo.getCardNo());
                    recharge_type.setText("充值类型：" + termAllVerifyInfo.getOrderName());
                    if (termAllVerifyInfo.getPayType() == null) {
                        pay_type.setText("");
                    } else {
                        pay_type.setText("支付方式：" + termAllVerifyInfo.getPayType());
                    }
                    time.setText(termAllVerifyInfo.getCreateTime() + "");
                    String orderStatusName = termAllVerifyInfo.getOrderStatusName();
                    if (orderStatusName == null) {
                        mpOrderStatusStr.setText("未写卡");
                    } else {
                        mpOrderStatusStr.setText(termAllVerifyInfo.getOrderStatusName() + "");
                    }
                }else{
                    rlRecharge.setVisibility(View.VISIBLE);
                }
            }

            @Override
            protected void onFailure(PowerCheckOrderRes response) {
                super.onFailure(response);
                dismissLoadingDialog();
                rlRecharge.setVisibility(View.VISIBLE);
//                ((IPowerContract.IPowerView) mView).checkOrderFail(response.getMessage());
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });

    }



    private String cardNo;
    private String asn;//ic 卡序列号
    private String cardType;//卡应用类型标识
    private String rndnumber2;//四字节伪随机数
    private String cardTradeNo;//联机交易号
    private String tradeType;
    private String keyVersion;//秘钥版本号
    private String arithIndex;//算法标志
    private String mac1;
    private String cardOldBal;
    String userId;

    private void requestMac2() {

        PowerGetMac2Req powerGetMac2Req = new PowerGetMac2Req();
        powerGetMac2Req.setAccess_token(access_token);
        powerGetMac2Req.setArith_index(arithIndex);
        powerGetMac2Req.setAsn(asn);
        powerGetMac2Req.setCard_no(cardNo);
        powerGetMac2Req.setCard_old_balance(cardOldBalance+"" );
        powerGetMac2Req.setCard_trade_no(cardTradeNo);
        powerGetMac2Req.setCard_type("01");
        powerGetMac2Req.setKey_version(keyVersion);
        powerGetMac2Req.setMac1(mac1);
        powerGetMac2Req.setOrder_no(termAllVerifyInfo.getOrderNo());
        powerGetMac2Req.setRndnumber2(rndnumber2);
        powerGetMac2Req.setSerialNo("");
        powerGetMac2Req.setTrade_money(tradeMoney);
        powerGetMac2Req.setSupply_time("");
        String json = new Gson().toJson(powerGetMac2Req);
        L.e(Constant.TAG, "powerGetMac2----req" + json);
        btn_write.setEnabled(true);
        mNetworkDateSource.termTopupMac2(powerGetMac2Req, new SubscribeResult<PowerGetMac2Res>() {
            @Override
            protected void onOk(PowerGetMac2Res response) {

                dismissLoadingDialog();

                String toJson = new Gson().toJson(response);
                powerGetMac2Res = response;
                L.e(Constant.TAG, "termTopupMac2---->" + toJson);
                writeCardInfo();
            }

            @Override
            protected void onFailure(PowerGetMac2Res response) {
                super.onFailure(response);
                dismissLoadingDialog();
                StringCommonUtil.showMsg(CardInfoActivity.this, response.getMessage());
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });

    }

    @Override
    protected void setListener() {
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                AppManager.getAppManager().finishActivity(CardInfoActivity.this);
                finish();
            }

        });

        btn_write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                progressLayout.setVisibility(View.VISIBLE);
                btn_write.setEnabled(false);
                showLoadDialog("正在写卡...");
                String balance = String.format("%08x",tradeMoney);
                getCardTradeInfo(balance);
          //      topUpInit("8");
//                requestMac2();
            }
        });

        btnRecharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (!isPaying) {
//                    isPaying = true;
                if (mode == 0) {
                    Toast.makeText(CardInfoActivity.this, "", Toast.LENGTH_SHORT).show();
                    StringCommonUtil.showMsg(CardInfoActivity.this, "请选择充值方式");
                    return;
                } else if (mode == 6) {
                    if (TextUtils.isEmpty(etPwd.getText())) {
                        StringCommonUtil.showMsg(CardInfoActivity.this, "请输入密码");
                        return;
                    } else {
                        recharge();
                    }
                } else if (mode == 2) {
                    if (TextUtils.isEmpty(etRecharge.getText()) || Double.parseDouble(etRecharge.getText().toString()) <= 0) {
                        StringCommonUtil.showMsg(CardInfoActivity.this, "请输入正确的充值金额");
                        return;
                    } else {
                        recharge();
                    }
                } else if (mode == 1) {
                    if (TextUtils.isEmpty(etRecharge.getText()) || Double.parseDouble(etRecharge.getText().toString()) <= 0) {
                        StringCommonUtil.showMsg(CardInfoActivity.this, "请输入正确的充值金额");
                        return;
                    } else if (TextUtils.isEmpty(etPwd.getText())) {
                        StringCommonUtil.showMsg(CardInfoActivity.this, "请输入密码");
                        return;
                    } else {
                        recharge();
                    }
                }
            }
        });

        btn_read_card.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
         //       findCard();
                loadCardInfo();

            }
        });

        text_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
      //          findCard();
                loadCardInfo();
            }
        });

        rg_mode.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (pm_zfb.getId() == checkedId) {
                    mode = 2;
                    etRecharge.setText("");
                    etPwd.setText("");
                    etRecharge.setVisibility(View.VISIBLE);
                    etPwd.setVisibility(View.GONE);
                } else if (pm_czk.getId() == checkedId) {
                    mode = 6;
                    etRecharge.setText("");
                    etPwd.setText("");
                    etRecharge.setVisibility(View.GONE);
                    etPwd.setVisibility(View.VISIBLE);
                    etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else if (pm_zyzh.getId() == checkedId) {
                    mode = 1;
                    etRecharge.setText("");
                    etPwd.setText("");
                    etRecharge.setVisibility(View.VISIBLE);
                    etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    etPwd.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void recharge() {
        showLoadDialog("正在充值...");
        String psd = etPwd.getText().toString();
        PowerRechargeReq powerRechargeReq = new PowerRechargeReq();
        powerRechargeReq.setAccess_token(access_token);
        powerRechargeReq.setCard_no(cardNo);
        powerRechargeReq.setPay_mode(mode + "");
//        if (mode == 2) {
//            int treMoney = (int) (Float.parseFloat(etRecharge.getText().toString()));
//            boolean is = treMoney % 50 == 0;
//            if (!is) {
//                dismissLoadingDialog();
//                Toast.makeText(this, "支付宝充值必须是50的倍数", Toast.LENGTH_SHORT).show();
//                return;
//            }
//        }
        if (mode == 1 || mode == 2) {
            int treMoney = (int) (Float.parseFloat(etRecharge.getText().toString()));
            powerRechargeReq.setTrade_money(treMoney * 100 + "");
        }
        powerRechargeReq.setPrepaid_card_password(psd);
        powerRechargeReq.setChannel_type("1");
        powerRechargeReq.setSpecial_account_password(psd);
        powerRechargeReq.setOrigin(2);

        String json1 = new Gson().toJson(powerRechargeReq);
        L.e(Constant.TAG, "powerRecharge--------->" + json1);
        mNetworkDateSource.bluetoothOrder(powerRechargeReq, new SubscribeResult<PowerRechargeRes>() {
            @Override
            protected void onOk(PowerRechargeRes response) {

                dismissLoadingDialog();
                String json = new Gson().toJson(response);
                L.e(Constant.TAG, "powerRecharge-----req" + json);

                if (mode == 1 || mode == 6) {
                    Message message = new Message();
                    message.what = RQF_PAY;
                    handler.sendMessage(message);
                } else if (mode == 2) {
                    extend = response.getExtend();
                    Message message = new Message();
                    message.what = 15;
                    handler.sendMessage(message);
                }


//                ((IPowerContract.IPowerView) mView).powerRechargeSucc(response);
            }

            @Override
            protected void onFailure(PowerRechargeRes response) {
                super.onFailure(response);

                dismissLoadingDialog();
                Toast.makeText(CardInfoActivity.this, response.getMessage(), Toast.LENGTH_SHORT).show();
//                ((IPowerContract.IPowerView) mView).powerRechargeFail(response.getMessage());
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

//                ((IPowerContract.IPowerView) mView).powerRechargeFail(throwable.getMessage());
            }
        });

    }

    //处理支付宝回调结果
    private void handlerAipay() {
        try {
            new Thread() {
                public void run() {
//                    String orderStr = prepayOrderAddPayRes.getPayConfig().getSign();
                    PayTask alipay = new PayTask(CardInfoActivity.this);
                    // 设置为沙箱模式，不设置默认为线上环境
                    // alipay.setSandBox(true);
                    String result = alipay.pay(extend, true);
                    Message message = new Message();
                    message.what = RQF_PAY;
                    message.obj = result;
                    handler.sendMessage(message);

                }
            }.start();
        } catch (Exception ex) {
            ex.printStackTrace();

            Toast.makeText(CardInfoActivity.this, "充值失败",
                    Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
//            setResult(RESULT_OK);
            AppManager.getAppManager().finishActivity(CardInfoActivity.this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void finish() {
        try {
   //         SearchDeviceActivity.bleBusiness.disConnectDevice();
        } catch (Exception e) {
            Toast.makeText(CardInfoActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        super.finish();
    }
}

